<?php

namespace common\models\datas;

use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
use yii\web\IdentityInterface;
use common\components\extenders\MenuManage;

/**
 * This is the model class for table "{{%admin}}".
 *
 * @property integer $id
 * @property string $username
 * @property string $password
 * @property string $email
 * @property string $name
 * @property integer $created_at
 * @property integer $updated_at
 * @property integer $last_login_at
 * @property string $last_login_id
 * @property integer $is_default
 * @property integer $status
 */
class Admin extends \common\components\bases\BaseModel implements IdentityInterface
{

    const STATUS_ACTIVE = 1;

    public $password_r;

    /**
     * @inheritdoc
     */

    public static function tableName()
    {
        return '{{%admin}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'email', 'role'], 'required', 'on' => ['create', 'update']],
            [['username', 'email'], 'required', 'on' => 'update'],

            ['username', 'string', 'min' => 4, 'max' => 15,'on' => ['create', 'update']],
            [['username'], 'username_check'],

            [['created_at', 'updated_at', 'last_login_at', 'is_default', 'status'], 'integer'],
            [['username', 'last_login_id'], 'string', 'max' => 50],
            [['password'], 'string', 'max' => 60, 'min' => 6],
            [['email'], 'email'],
            [['name'], 'string', 'max' => 20],
            [['role'], 'string', 'max' => 50],
            [['password_r', 'password'], 'required', 'message' => '请输入确认密码', 'on' => 'create'],
            [['password_r'], 'password_check'],
            [['username', 'email'], 'unique'],

        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('frontend', '自动编号'),
            'username' => Yii::t('frontend', '用户名'),
            'password' => Yii::t('frontend', '密码'),
            'password_r' => Yii::t('frontend', '确认密码'),
            'email' => Yii::t('frontend', '邮箱'),
            'name' => Yii::t('frontend', '真实姓名'),
            'created_at' => Yii::t('frontend', '创建时间'),
            'updated_at' => Yii::t('frontend', '修改时间'),
            'last_login_at' => Yii::t('frontend', '最后登录时间'),
            'last_login_id' => Yii::t('frontend', '最后登录IP'),
            'is_default' => Yii::t('frontend', '默认系统管理员'),
            'status' => Yii::t('frontend', '状态'),
            'role' => Yii::t('frontend', '角色'),
        ];
    }

    public function fields()
    {
        $fields = parent::fields();
        $fields['status'] = function () {
            switch ($this->status) {
                case 0:
                    return \Yii::t('frontend', '已停用');
                case 1:
                    return \Yii::t('frontend', '已激活');
            }
        };
        $fields['created_at'] = function () {
            return \Yii::$app->formatter->asDatetime($this->created_at);
        };
        unset($fields['password']);
        return $fields;
    }

    public function extraFields()
    {
        return [
            'operate' => function () {
                return (new MenuManage(MenuManage::RECORD_ITEM_TOOLBAR, $this->attributes))->create();
            },
        ];
    }

    public function password_check($attribute)
    {
        if ($this->password !== $this->$attribute) {
            $this->addError($attribute, Yii::t('frontend', '确认密码必须与新密码相同'));
        }
    }

    public function username_check($attribute){
        if(preg_match('/^[1-9]\d*$/',$this->$attribute)) {
            $this->addError($attribute, Yii::t('frontend', '不可单纯为数字'));
        }elseif(preg_match('/[^a-zA-Z0-9_^\x00-\x80]+/',$this->$attribute)){
            $this->addError($attribute, Yii::t('frontend', '只支持字母、中文、数字、下划线'));
        }
    }


    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
                ],
            ],
        ]);
    }


    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }

    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    public function getId()
    {
        return $this->getPrimaryKey();
    }

    public function getAuthKey()
    {
        return $this->auth_key;
    }

    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password);
    }

    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
    }


}


